package com.dongnaoedu.rpc.redis.server;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.ReflectionUtils;

import com.dongnaoedu.rpc.redis.Channel;
import com.dongnaoedu.rpc.redis.spring.ApplicationContextHolder;
import com.dongnaoedu.rpc.redis.spring.ProviderListener;

public class HanderResult {
	
	private final static Log log = LogFactory.getLog(ProviderListener.class);

	private final static int ok = 0;

	private final static int error = -1;
	
	/**
	 * All results are processed including all known exceptions.
	 * 
	 * @param result
	 * @return
	 */
	public static ServerMessage handerResult(String messageId, Object result) {
		if (result instanceof Exception) {
			Exception ex = (Exception) result;
			log.error("Provider deal exception : ", ex);
			if (result instanceof IllegalArgumentException) {
				// java.lang.IllegalArgumentException: argument type mismatch
			} else {
				// java.lang.RuntimeException:
			}
			return new ServerMessage(error, messageId, ex.getMessage());
		} else {
			log.info("Provider deal result success : " + result);
			if (result instanceof String) {
				return new ServerMessage(ok, messageId, new String((String) result));
				// else if ...
			} else {
				return new ServerMessage(ok, messageId, new String(result.toString()));
			}
		}
	}
	/**
	 * Reflection execution method and processing method returns the result of ServerMessage.
	 * 
	 * @param messageId
	 * @param className
	 * @param methodName
	 * @param args
	 * @return
	 * 
	 */
	public static ServerMessage reflectInvoke(String messageId, String className, String methodName, Object[] args) {
		try {
			Channel channel = new ServerChannel(className, methodName, args);
			Object target = ApplicationContextHolder.getApplicationContext().getBean(channel.getInterface());
			return handerResult(messageId, ReflectionUtils.invokeMethod(channel.getMethod(), target, args));
		} catch (Exception e) {
			return handerResult(messageId, e);
		}
	}
}
